package com.cmdi.service.impl;

import com.cmdi.constant.CommonConstant;
import com.cmdi.domain.CustomerUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 用户信息实现类
 * @Author: gaozb
 */
@Service
public class UserServiceDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String loginType = requestAttributes.getRequest().getParameter(CommonConstant.LOGIN_TYPE);
        if(StringUtils.isEmpty(loginType)) {
            throw new AuthenticationServiceException("登录类型不能为空");
        }
        CustomerUserDetails userDetails = null;
        try {
            switch (loginType) {
                case CommonConstant.ADMIN_TYPE:
                    userDetails = loadAdminUserByUsername(username);
                    break;
                case CommonConstant.USER_TYPE:
                    throw new AuthenticationServiceException("暂不支持的登录方式:" + loginType);
                    //break;
                default:
                    throw new AuthenticationServiceException("暂不支持的登录方式:" + loginType);
            }
        } catch (DataAccessException e) {
            throw new UsernameNotFoundException("用户不存在:" + username);
        }
        return userDetails;
    }
    public CustomerUserDetails loadAdminUserByUsername(String username)  {
        return jdbcTemplate.queryForObject(CommonConstant.QUERY_ADMIN_SQL, new RowMapper<CustomerUserDetails>() {
            @Override
            public CustomerUserDetails mapRow(ResultSet resultSet, int i) throws SQLException {
                if(resultSet.wasNull()) {
                    throw new UsernameNotFoundException("用户不存在:" + username);
                }
                Long id = resultSet.getLong("id");
                String pass = resultSet.getString("password");
                int status = resultSet.getInt("status");
                boolean enabled = status == 1 ? true : false;
                boolean disabled = status == 2 ? false : true;
                boolean expired = status == 3 ? false : true;
                return new CustomerUserDetails(
                        username, pass,enabled,expired, true, disabled, getAdminUserPermsByUserId(id), id);
            }
        }, username);
    }
    public Collection<? extends GrantedAuthority> getAdminUserPermsByUserId(Long id)  {
        List<String> permissions = jdbcTemplate.queryForList(CommonConstant.QUERY_ADMIN_PERMS_SQL, String.class, id);
        return permissions.stream().distinct().map(perms -> new SimpleGrantedAuthority(perms)).collect(Collectors.toSet());
    }
}